package com.ceres.customer.service.impl;

import com.ceres.customer.dao.CustRoleMapper;
import com.ceres.customer.dao.CustUserMapper;
import com.ceres.customer.pojo.Role;
import com.ceres.customer.pojo.User;
import com.ceres.customer.service.CustUserService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCrypt;
import org.springframework.stereotype.Service;

import java.util.LinkedHashSet;
import java.util.List;

@Service
public class CustUserServiceImpl implements CustUserService {

    @Autowired
    private CustUserMapper custUserMapper;

    @Autowired
    private CustRoleMapper custRoleMapper;

    /**
     * 修改农业组织用户
     *
     * @param id
     */
    @Override
    public void update(int id) {
        //密码加盐加密
        String gensalt = BCrypt.gensalt();
        String password = BCrypt.hashpw("123456", gensalt);
        custUserMapper.updatePasswordById(id, password);
    }

    /**
     * 分页模糊查询
     *
     * @param keyword
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public Page findPage(String keyword, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        return (Page<User>) custUserMapper.findByKeyWord(keyword);
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @Override
    public User findById(int id) {
        //根据用户id获取用户信息
        User user = custUserMapper.selectByPrimaryKey(id);
        //根据用户id在关联表中获取相关的角色信息集合
        LinkedHashSet<Role> roleList = custRoleMapper.getByUserId(id);
        //将角色集合封装进用户实体中
        user.setRoles(roleList);
        return user;
    }

    /**
     * 查询所有
     *
     * @return
     */
    @Override
    public List<User> findAll() {
        return custUserMapper.selectAll();
    }

}
